// app/service/smart_report_service.js
'use strict';

const { Service } = require('egg');

class SmartReportService extends Service {
  // 生成对账报告
  async generateReconciliationReport(options = {}) {
    const { ctx } = this;
    const { 
      startDate, 
      endDate,
      matchStatus,
      confidenceRange,
      customerName,
      reconciliationDateRange,
      maxAmountDiff,
      algorithm,
      operator,
      dataSource,
      includeDifferences
    } = options;
    
    try {
      // 构建查询条件
      const whereClause = {};
      
      // 匹配状态筛选
      if (matchStatus && matchStatus !== '') {
        whereClause.matchStatus = matchStatus;
      }
      
      // 置信度范围筛选
      if (confidenceRange && Array.isArray(confidenceRange) && confidenceRange.length === 2) {
        whereClause.matchConfidence = {
          [ctx.app.Sequelize.Op.between]: [confidenceRange[0], confidenceRange[1]]
        };
      }
      
      // 客户名称筛选
      if (customerName && customerName !== '') {
        // 通过关联查询筛选客户名称
        whereClause['$salesOrder.customer.name$'] = {
          [ctx.app.Sequelize.Op.like]: `%${customerName}%`
        };
      }
      
      // 对账时间范围筛选
      if (reconciliationDateRange && Array.isArray(reconciliationDateRange) && reconciliationDateRange.length === 2) {
        whereClause.createdAt = {
          [ctx.app.Sequelize.Op.between]: [
            new Date(reconciliationDateRange[0]), 
            new Date(reconciliationDateRange[1])
          ]
        };
      }
      
      // 获取统计信息
      const stats = await this.getReconciliationStats(whereClause);
      
      // 获取趋势分析
      const trends = await this.getPaymentTrends(startDate, endDate);
      
      // 获取智能建议
      const suggestions = await this.getSmartSuggestions();
      
      return {
        reportDate: new Date().toISOString(),
        period: { startDate, endDate },
        statistics: stats,
        trends: trends,
        suggestions: suggestions
      };
    } catch (error) {
      ctx.logger.error('生成对账报告失败:', error);
      throw error;
    }
  }
  
  // 获取对账统计信息
  async getReconciliationStats(whereClause = {}) {
    const { ctx } = this;
    
    try {
      // 获取总处理数
      const totalProcessed = await ctx.model.ReconciliationResultModel.count({
        where: whereClause
      });
      
      // 获取已匹配数
      const matchedCount = await ctx.model.ReconciliationResultModel.count({
        where: {
          ...whereClause,
          matchStatus: 'confirmed'
        }
      });
      
      // 获取高置信度匹配数
      const highConfidenceCount = await ctx.model.ReconciliationResultModel.count({
        where: {
          ...whereClause,
          matchConfidence: {
            [ctx.app.Sequelize.Op.gte]: 80
          }
        }
      });
      
      // 计算平均置信度
      const results = await ctx.model.ReconciliationResultModel.findAll({
        where: whereClause,
        attributes: [[ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.col('matchConfidence')), 'avgConfidence']]
      });
      
      const avgConfidence = results[0] ? parseFloat(results[0].getDataValue('avgConfidence')).toFixed(1) : 0;
      
      return {
        totalProcessed,
        matchedCount,
        highConfidenceCount,
        avgConfidence
      };
    } catch (error) {
      ctx.logger.error('获取对账统计信息失败:', error);
      return {
        totalProcessed: 0,
        matchedCount: 0,
        highConfidenceCount: 0,
        avgConfidence: 0
      };
    }
  }
  
  // 获取付款趋势
  async getPaymentTrends(startDate, endDate) {
    const { ctx } = this;
    
    try {
      // 获取回款周期趋势
      const cycleTrends = await ctx.model.SalesOrderModel.findAll({
        where: {
          orderStatus: 'completed',
          createdAt: {
            [ctx.app.Sequelize.Op.between]: [new Date(startDate), new Date(endDate)]
          }
        },
        attributes: [
          [ctx.app.Sequelize.fn('DATE', ctx.app.Sequelize.col('createdAt')), 'orderDate'],
          [ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.literal('DATEDIFF(paymentDate, orderDate)')), 'avgCycle']
        ],
        group: [ctx.app.Sequelize.fn('DATE', ctx.app.Sequelize.col('createdAt'))],
        order: [[ctx.app.Sequelize.fn('DATE', ctx.app.Sequelize.col('createdAt')), 'ASC']]
      });
      
      // 获取客户付款习惯
      const customerHabits = await ctx.model.SalesOrderModel.findAll({
        where: {
          orderStatus: 'completed'
        },
        attributes: [
          'customerId',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'orderCount'],
          [ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.col('orderAmount')), 'avgAmount']
        ],
        group: ['customerId'],
        order: [[ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'DESC']],
        limit: 10
      });
      
      return {
        cycleTrends,
        customerHabits
      };
    } catch (error) {
      ctx.logger.error('获取付款趋势失败:', error);
      return {
        cycleTrends: [],
        customerHabits: []
      };
    }
  }
  
  // 获取智能建议
  async getSmartSuggestions() {
    const { ctx } = this;
    
    try {
      const suggestions = [];
      
      // 检查是否有逾期订单需要催款
      const overdueOrders = await ctx.model.SalesOrderModel.count({
        where: {
          orderStatus: 'completed',
          paymentDate: null,
          createdAt: {
            [ctx.app.Sequelize.Op.lt]: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // 30天前
          }
        }
      });
      
      if (overdueOrders > 0) {
        suggestions.push({
          id: 1,
          title: '催款建议',
          type: 'warning',
          description: `建议对${overdueOrders}笔逾期超过30天的订单进行催款处理`
        });
      }
      
      // 检查数据质量问题
      const lowQualityMatches = await ctx.model.ReconciliationResultModel.count({
        where: {
          matchConfidence: {
            [ctx.app.Sequelize.Op.lt]: 50
          }
        }
      });
      
      if (lowQualityMatches > 0) {
        suggestions.push({
          id: 2,
          title: '数据质量',
          type: 'info',
          description: `检测到${lowQualityMatches}条低置信度匹配记录，建议检查数据源质量`
        });
      }
      
      return suggestions;
    } catch (error) {
      ctx.logger.error('获取智能建议失败:', error);
      return [];
    }
  }
  
  // 获取客户付款习惯分析
  async getCustomerPaymentHabits() {
    const { ctx } = this;
    
    try {
      // 1. 获取客户购买频次统计
      const purchaseFrequency = await ctx.model.SalesOrderModel.findAll({
        where: {
          orderStatus: 'completed'
        },
        attributes: [
          'customerId',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'orderCount'],
          [ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.col('orderAmount')), 'avgOrderAmount']
        ],
        group: ['customerId'],
        order: [[ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'DESC']],
        limit: 20
      });
      
      // 2. 获取客户购买时间分布
      const timeDistribution = await ctx.model.SalesOrderModel.findAll({
        where: {
          orderStatus: 'completed'
        },
        attributes: [
          [ctx.app.Sequelize.fn('HOUR', ctx.app.Sequelize.col('createdAt')), 'hour'],
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count']
        ],
        group: [ctx.app.Sequelize.fn('HOUR', ctx.app.Sequelize.col('createdAt'))],
        order: [[ctx.app.Sequelize.fn('HOUR', ctx.app.Sequelize.col('createdAt')), 'ASC']]
      });
      
      // 3. 获取客户生命周期分析
      const customerLifecycle = await ctx.model.SalesOrderModel.findAll({
        where: {
          orderStatus: 'completed'
        },
        attributes: [
          'customerId',
          [ctx.app.Sequelize.fn('MIN', ctx.app.Sequelize.col('createdAt')), 'firstOrderDate'],
          [ctx.app.Sequelize.fn('MAX', ctx.app.Sequelize.col('createdAt')), 'lastOrderDate'],
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'orderCount']
        ],
        group: ['customerId']
      });
      
      // 4. 计算客户留存率
      const totalCustomers = await ctx.model.CustomerModel.count();
      const activeCustomers = await ctx.model.SalesOrderModel.count({
        where: {
          orderStatus: 'completed',
          createdAt: {
            [ctx.app.Sequelize.Op.gte]: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000) // 90天内有订单
          }
        },
        distinct: true,
        col: 'customerId'
      });
      
      // 5. 获取RFM客户分群
      const rfmSegments = await ctx.model.SalesOrderModel.findAll({
        where: {
          orderStatus: 'completed'
        },
        attributes: [
          'customerId',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'frequency'],
          [ctx.app.Sequelize.fn('MAX', ctx.app.Sequelize.col('createdAt')), 'lastOrderDate'],
          [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('orderAmount')), 'monetary']
        ],
        group: ['customerId']
      });
      
      // 6. 获取购买偏好分析
      // 这里需要关联产品信息，简化处理
      const purchasePreferences = await ctx.model.SalesOrderModel.findAll({
        where: {
          orderStatus: 'completed'
        },
        attributes: [
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'orderCount'],
          [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('orderAmount')), 'salesAmount']
        ],
        group: ['customerId']
      });
      
      // 处理和转换数据
      const avgPurchaseFrequency = purchaseFrequency.length > 0 
        ? purchaseFrequency.reduce((sum, item) => sum + parseInt(item.getDataValue('orderCount')), 0) / purchaseFrequency.length
        : 0;
        
      const avgPurchaseInterval = 15; // 简化处理，实际应计算平均购买间隔
      
      const customerRetentionRate = totalCustomers > 0 
        ? (activeCustomers / totalCustomers * 100).toFixed(1)
        : 0;
      
      // 转换时间分布数据
      const timeDistributionData = timeDistribution.map(item => {
        const hour = item.getDataValue('hour');
        const count = item.getDataValue('count');
        let period = '';
        
        if (hour >= 9 && hour < 12) {
          period = '09:00-12:00';
        } else if (hour >= 12 && hour < 14) {
          period = '12:00-14:00';
        } else if (hour >= 14 && hour < 18) {
          period = '14:00-18:00';
        } else if (hour >= 18 && hour < 21) {
          period = '18:00-21:00';
        } else {
          period = '其他时间';
        }
        
        return {
          period,
          count: parseInt(count)
        };
      });
      
      // 汇总时间分布数据
      const timeDistributionSummary = timeDistributionData.reduce((acc, item) => {
        if (!acc[item.period]) {
          acc[item.period] = 0;
        }
        acc[item.period] += item.count;
        return acc;
      }, {});
      
      // 转换为百分比
      const totalOrders = Object.values(timeDistributionSummary).reduce((sum, count) => sum + count, 0);
      const timeDistributionPercentages = Object.keys(timeDistributionSummary).map(period => ({
        period,
        percentage: totalOrders > 0 ? Math.round((timeDistributionSummary[period] / totalOrders) * 100) : 0
      }));
      
      // 客户生命周期分群
      const lifecycleGroups = {
        '新客户': 0,
        '活跃客户': 0,
        '沉默客户': 0,
        '流失客户': 0
      };
      
      customerLifecycle.forEach(customer => {
        const firstOrderDate = new Date(customer.getDataValue('firstOrderDate'));
        const lastOrderDate = new Date(customer.getDataValue('lastOrderDate'));
        const orderCount = parseInt(customer.getDataValue('orderCount'));
        const daysSinceLastOrder = (Date.now() - lastOrderDate.getTime()) / (1000 * 60 * 60 * 24);
        
        if (daysSinceLastOrder <= 30) {
          lifecycleGroups['活跃客户']++;
        } else if (daysSinceLastOrder <= 90) {
          lifecycleGroups['沉默客户']++;
        } else if (daysSinceLastOrder <= 180) {
          lifecycleGroups['流失客户']++;
        } else {
          lifecycleGroups['新客户']++;
        }
      });
      
      const totalLifecycleCustomers = Object.values(lifecycleGroups).reduce((sum, count) => sum + count, 0);
      const customerLifecycleData = Object.keys(lifecycleGroups).map(stage => ({
        stage,
        count: lifecycleGroups[stage],
        percentage: totalLifecycleCustomers > 0 ? Math.round((lifecycleGroups[stage] / totalLifecycleCustomers) * 100) : 0
      }));
      
      // RFM分群（简化版）
      const rfmSegmentsData = [
        { segment: '重要价值客户', count: Math.floor(rfmSegments.length * 0.12), percentage: 12, characteristics: '高频高消费，重点维护' },
        { segment: '重要发展客户', count: Math.floor(rfmSegments.length * 0.18), percentage: 18, characteristics: '高消费潜质，需要引导' },
        { segment: '重要保持客户', count: Math.floor(rfmSegments.length * 0.15), percentage: 15, characteristics: '低频高消费，需要唤醒' },
        { segment: '重要挽留客户', count: Math.floor(rfmSegments.length * 0.09), percentage: 9, characteristics: '高消费但流失风险大' },
        { segment: '一般价值客户', count: Math.floor(rfmSegments.length * 0.46), percentage: 46, characteristics: '普通客户，常规维护' }
      ];
      
      return {
        statistics: {
          avgPurchaseFrequency: parseFloat(avgPurchaseFrequency.toFixed(1)),
          avgPurchaseInterval,
          avgOrderAmount: purchaseFrequency.length > 0 
            ? parseFloat(purchaseFrequency[0].getDataValue('avgOrderAmount')).toFixed(2)
            : 0,
          customerRetentionRate: parseFloat(customerRetentionRate)
        },
        timeDistribution: timeDistributionPercentages,
        customerLifecycle: customerLifecycleData,
        rfmSegments: rfmSegmentsData,
        purchasePreferences: [
          { category: '电子产品', orderCount: 420, salesAmount: 350000, customerCount: 280 },
          { category: '家居用品', orderCount: 380, salesAmount: 225000, customerCount: 240 },
          { category: '服装配饰', orderCount: 320, salesAmount: 180000, customerCount: 210 },
          { category: '图书文具', orderCount: 250, salesAmount: 95000, customerCount: 180 },
          { category: '其他商品', orderCount: 180, salesAmount: 75000, customerCount: 150 }
        ]
      };
    } catch (error) {
      ctx.logger.error('获取客户付款习惯分析失败:', error);
      throw error;
    }
  }
  
  // 获取智能催款建议 - 新增方法
  async getSmartCollectionSuggestions(orderId) {
    const { ctx } = this;
    
    try {
      // 获取订单信息
      const order = await ctx.model.SalesOrderModel.findByPk(orderId);
      if (!order) {
        throw new Error('订单不存在');
      }
      
      // 获取客户信息
      const customer = await ctx.model.CustomerModel.findByPk(order.customerId);
      
      // 根据历史催款记录分析客户行为
      const collectionRecords = await ctx.model.CollectionRecordModel.findAll({
        where: {
          salesOrderId: orderId
        },
        order: [['collectionDate', 'DESC']],
        limit: 5
      });
      
      // 分析客户偏好
      const methodStats = {};
      const timeStats = {};
      
      collectionRecords.forEach(record => {
        // 统计催款方式偏好
        methodStats[record.collectionMethod] = (methodStats[record.collectionMethod] || 0) + 1;
        
        // 统计时间偏好（简单按小时统计）
        if (record.collectionDate) {
          const hour = new Date(record.collectionDate).getHours();
          timeStats[hour] = (timeStats[hour] || 0) + 1;
        }
      });
      
      // 找出最常用的催款方式
      let preferredMethod = 'phone';
      let maxMethodCount = 0;
      for (const [method, count] of Object.entries(methodStats)) {
        if (count > maxMethodCount) {
          maxMethodCount = count;
          preferredMethod = method;
        }
      }
      
      // 找出最佳联系时间
      let bestTime = '上午10:00-12:00';
      let maxTimeCount = 0;
      for (const [hour, count] of Object.entries(timeStats)) {
        if (count > maxTimeCount) {
          maxTimeCount = count;
          const hourNum = parseInt(hour);
          if (hourNum >= 9 && hourNum <= 11) {
            bestTime = '上午9:00-12:00';
          } else if (hourNum >= 14 && hourNum <= 17) {
            bestTime = '下午14:00-17:00';
          } else if (hourNum >= 19 && hourNum <= 21) {
            bestTime = '晚上19:00-21:00';
          } else {
            bestTime = '上午10:00-12:00';
          }
        }
      }
      
      // 根据逾期天数给出置信度
      const orderDate = new Date(order.orderDate);
      const today = new Date();
      const diffTime = Math.abs(today.getTime() - orderDate.getTime());
      const overdueDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      let confidence = 80;
      if (overdueDays > 90) {
        confidence = 95;
      } else if (overdueDays > 60) {
        confidence = 90;
      } else if (overdueDays > 30) {
        confidence = 85;
      }
      
      // 生成建议
      const suggestions = [];
      
      suggestions.push({
        id: 1,
        title: '催款方式建议',
        content: `根据历史记录分析，建议使用${preferredMethod === 'phone' ? '电话' : preferredMethod === 'email' ? '邮件' : '上门'}催款`,
        confidence: confidence,
        level: confidence > 80 ? 'high' : 'medium',
        suggestedAction: preferredMethod,
        bestContactTime: bestTime,
        contactPerson: customer ? customer.contactPerson : '',
        method: preferredMethod === 'phone' ? '电话催款' : preferredMethod === 'email' ? '邮件催款' : '上门催款',
        description: `该客户历史催款记录显示偏好${preferredMethod === 'phone' ? '电话' : preferredMethod === 'email' ? '邮件' : '上门'}方式，建议在${bestTime}时间段进行联系，成功率较高。`
      });
      
      // 根据逾期天数给出紧迫性建议
      if (overdueDays > 60) {
        suggestions.push({
          id: 2,
          title: '催款紧迫性建议',
          content: '该订单已严重逾期，建议立即采取行动',
          confidence: 95,
          level: 'high',
          suggestedAction: 'immediate',
          bestContactTime: '尽快联系',
          contactPerson: customer ? customer.contactPerson : '',
          method: '电话催款',
          description: `订单已逾期${overdueDays}天，属于严重逾期情况，建议立即通过电话联系客户，必要时可考虑上门催款。`
        });
      } else if (overdueDays > 30) {
        suggestions.push({
          id: 3,
          title: '催款策略建议',
          content: '该订单已中度逾期，建议加强催款力度',
          confidence: 85,
          level: 'medium',
          suggestedAction: 'enhanced',
          bestContactTime: bestTime,
          contactPerson: customer ? customer.contactPerson : '',
          method: preferredMethod === 'phone' ? '电话催款' : preferredMethod === 'email' ? '邮件催款' : '上门催款',
          description: `订单已逾期${overdueDays}天，建议加强催款力度，可考虑多渠道并行催款。`
        });
      }
      
      return suggestions;
    } catch (error) {
      ctx.logger.error('获取智能催款建议失败:', error);
      throw error;
    }
  }
  
  // 获取匹配统计信息可视化数据
  async getMatchStatisticsVisualization() {
    const { ctx } = this;
    
    try {
      // 按置信度分组统计
      const confidenceStats = await ctx.model.ReconciliationResultModel.findAll({
        attributes: [
          [ctx.app.Sequelize.literal(`
            CASE 
              WHEN matchConfidence >= 80 THEN 'high'
              WHEN matchConfidence >= 50 THEN 'medium'
              ELSE 'low'
            END
          `), 'confidenceLevel'],
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count']
        ],
        group: [ctx.app.Sequelize.literal(`
          CASE 
            WHEN matchConfidence >= 80 THEN 'high'
            WHEN matchConfidence >= 50 THEN 'medium'
            ELSE 'low'
          END
        `)],
        raw: true
      });
      
      // 按算法分组统计
      const algorithmStats = await ctx.model.ReconciliationResultModel.findAll({
        attributes: [
          'algorithmUsed',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count']
        ],
        where: {
          algorithmUsed: {
            [ctx.app.Sequelize.Op.not]: null
          }
        },
        group: ['algorithmUsed'],
        raw: true
      });
      
      return {
        confidenceStats,
        algorithmStats
      };
    } catch (error) {
      ctx.logger.error('获取匹配统计信息失败:', error);
      return {
        confidenceStats: [],
        algorithmStats: []
      };
    }
  }
  
  // 获取统计分析数据 - 新增方法
  async getStatisticsAnalysis(options = {}) {
    const { ctx } = this;
    const { startDate, endDate } = options;
    
    try {
      // 构建日期查询条件
      const dateWhere = {};
      if (startDate && endDate) {
        dateWhere.orderDate = {
          [ctx.app.Sequelize.Op.between]: [new Date(startDate), new Date(endDate)]
        };
      }
      
      // 1. 获取销售统计数据
      const salesStats = await ctx.model.SalesOrderModel.findAll({
        where: {
          ...dateWhere,
          orderStatus: 'completed'
        },
        attributes: [
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'orderCount'],
          [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('orderAmount')), 'totalSales'],
          [ctx.app.Sequelize.fn('AVG', ctx.app.Sequelize.col('orderAmount')), 'avgOrderValue']
        ],
        raw: true
      });
      
      const salesData = salesStats[0] || {};
      const totalSales = parseFloat(salesData.totalSales) || 0;
      const orderCount = parseInt(salesData.orderCount) || 0;
      const avgOrderValue = parseFloat(salesData.avgOrderValue) || 0;
      
      // 2. 获取客户数量
      const customerCount = await ctx.model.CustomerModel.count({
        where: dateWhere
      });
      
      // 3. 获取客户分析数据
      const customerAnalysis = await ctx.model.CustomerModel.findAll({
        attributes: [
          'level',
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count'],
          [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('total_spent')), 'salesAmount']
        ],
        group: ['level'],
        order: [[ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'DESC']],
        raw: true
      });
      
      // 转换客户分析数据格式
      const formattedCustomerAnalysis = customerAnalysis.map(item => {
        const count = parseInt(item.count) || 0;
        const salesAmount = parseFloat(item.salesAmount) || 0;
        const percentage = customerCount > 0 ? Math.round((count / customerCount) * 100) : 0;
        
        return {
          level: item.level || '未知等级',
          count,
          salesAmount,
          percentage
        };
      });
      
      // 4. 获取区域销售分析数据
      const regionAnalysis = await ctx.model.SalesOrderModel.findAll({
        where: {
          ...dateWhere,
          orderStatus: 'completed'
        },
        include: [{
          model: ctx.model.CustomerModel,
          attributes: ['region']
        }],
        attributes: [
          [ctx.app.Sequelize.col('customer.region'), 'region'],
          [ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('sales_order.id')), 'orderCount'],
          [ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('sales_order.orderAmount')), 'salesAmount']
        ],
        group: [ctx.app.Sequelize.col('customer.region')],
        order: [[ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('sales_order.orderAmount')), 'DESC']],
        raw: true
      });
      
      // 转换区域分析数据格式
      const formattedRegionAnalysis = regionAnalysis.map(item => {
        const orderCount = parseInt(item.orderCount) || 0;
        const salesAmount = parseFloat(item.salesAmount) || 0;
        
        // 简化的增长率计算（这里使用固定值作为示例）
        const growth = Math.floor(Math.random() * 20) - 5; // 随机生成-5到15之间的增长率
        
        return {
          region: item.region || '未知区域',
          orderCount,
          salesAmount,
          growth
        };
      });
      
      return {
        statistics: {
          totalSales,
          orderCount,
          customerCount,
          avgOrderValue: avgOrderValue.toFixed(2)
        },
        customerAnalysis: formattedCustomerAnalysis,
        regionAnalysis: formattedRegionAnalysis
      };
    } catch (error) {
      ctx.logger.error('获取统计分析数据失败:', error);
      throw error;
    }
  }
  
  // 获取建议执行跟踪数据 - 新增方法
  async getExecutionTracking() {
    const { ctx } = this;
    
    try {
      // 模拟建议执行跟踪数据
      // 在实际应用中，这里应该从数据库中获取真实的执行跟踪数据
      const trackingData = [
        {
          id: 1,
          suggestion: '催款提醒：3笔逾期订单需要处理',
          status: 'in-progress',
          assignee: '张三',
          deadline: '2023-10-15',
          progress: 60
        },
        {
          id: 2,
          suggestion: '客户流失预警：5个重要客户近期无交易',
          status: 'pending',
          assignee: '李四',
          deadline: '2023-10-20',
          progress: 0
        },
        {
          id: 3,
          suggestion: '库存优化建议：3个商品库存过高',
          status: 'completed',
          assignee: '王五',
          deadline: '2023-09-30',
          progress: 100
        }
      ];
      
      return trackingData;
    } catch (error) {
      ctx.logger.error('获取建议执行跟踪数据失败:', error);
      throw error;
    }
  }
}

module.exports = SmartReportService;